﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Newtonsoft.Json;

namespace Xmlt.Sample.Code
{


    public class JsonBinderAttribute : CustomModelBinderAttribute
    {


        public override IModelBinder GetBinder()
        {
            return new JsonModelBinder();
        }

        public class JsonModelBinder : IModelBinder
        {
            public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
            {
                try
                {
                    var inputStream = controllerContext.HttpContext.Request.InputStream;
                    using (var sr = new StreamReader(inputStream))
                    {
                        var json = sr.ReadToEnd();
                        return JsonConvert.DeserializeObject(json, bindingContext.ModelType);
                    }
                }
                catch
                {
                    return null;
                }
            }
        }
    }

    
}
